package com.sname.car.common.rest;

import com.sname.car.cache.CommonCacheUtil;
import com.sname.car.common.constants.Constants;
import com.sname.car.common.exception.CarException;
import com.sname.car.user.entity.UserElement;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Created By  醉美柳舞之众星捧月
 *
 * @author songx
 * @date 2018/9/21 22:27
 */
@RestController
public class BaseController {
    private Logger log = LoggerFactory.getLogger(getClass());
    @Autowired
    private CommonCacheUtil cacheUtil;

    /** 获取当前用户的信息 */
    protected UserElement getCurrentUserInformation() throws Exception {
        UserElement userElement = null;
        try {
            /** 获取当前的request  这一行代码是重点 ！**/
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
            String token = request.getHeader(Constants.TOKEN);
            if (StringUtils.isBlank(token)) {
                throw new CarException("客户端传递的token无效");
            }
            userElement = cacheUtil.getUserByToken(token);
        } catch (Exception e) {
            log.error("Fail to get Current User Information ");
        }
        return userElement;
    }
    /** 获取当前 IP  **/
    protected String getIpFromRequest(HttpServletRequest request){
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
    }
}
